import APIConfig from "../config/api";

import { wxToPromise } from "./wx";

import exceptionMessage from "../config/exception-message";

import cache from "../enum/cache"



class Http {
      
    static async request({url, data, method = "GET"}){
        wx.showLoading({
            title: '加载中...',
            mask: true,
        });
          
        let res = await wxToPromise("request", {
            url: APIConfig.baseUrl + url,
            data,
            method,
            header: {
                token: wx.getStorageSync(cache.TOKEN)
            },
            complete: () => {
                wx.hideLoading();
            }
        })

        if(res.statusCode < 400){
            return res.data.data
        }

        if(res.statusCode === 401){
            return
        }

        Http._showError(res.data.error_code, res.data.message)
    }

    static _showError(errorCode, message){
        let title
        const errorMessage = exceptionMessage[errorCode]
        title = errorMessage || message || "未知异常"
        title = typeof title === "object" ? Object.values(title).join() : title
        wx.showToast({
            title: '',
            icon: 'none',
            duration: 3000,
        });
          
    }
}

export default Http